package day19;

import java.io.IOException;
import java.io.InputStream;

/**
 * 自定义一个字节流的读取缓冲区
 * 
 * @author wangbiao
 * 
 */
public class CustomBufferedInputStream {

	private InputStream is;

	// 定义一个字节数组缓存每次读取到的字节
	private byte[] buf = new byte[1024 * 2];

	private int pos = 0, count = 0;
	
	//与上255，以免出现-1的情况
	private static final int BYTE_POSITION = 0xff;

	public CustomBufferedInputStream(InputStream is) {
		this.is = is;
	}

	public int read() throws IOException {
		if (count == 0) {
			count = is.read(buf);
			if(count < 0) {
				return -1;
			}
			pos = 0;
			byte b = buf[pos];
			pos++;
			count--;
			return b & BYTE_POSITION;
		} else if(count > 0) {
			byte b = buf[pos];
			pos++;
			count--;
			return b & BYTE_POSITION;
		}
		return -1;
	}

	public void close() throws IOException {
		if (null == is) {
			return;
		}
		is.close();
		is = null;
	}
}
